/**
 * Project: metacrumbs
 * File: CrumbsManager.java
 * Type: CrumbsManager
 * Author: unmarco
 * Created: Sep 8, 2011 3:36:37 PM
 */
package org.sensolab.metacrumbs.data;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.sensolab.metacrumbs.data.model.Attachment;
import org.sensolab.metacrumbs.data.model.MetaLocation;

import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;

/**
 * @author unmarco
 *
 */
public class CrumbsManager {

	@SuppressWarnings("unchecked")
	public static List<Attachment> getLocationAttachments(Key location) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Attachment> attachments = null;
		
		try {
			
			Query q = pm.newQuery(Attachment.class);
			q.setFilter("location == locationParam");
			q.declareParameters("com.google.appengine.api.datastore.Key locationParam");
			attachments = (List<Attachment>) q.execute(location);
		
		} catch (Exception e) {
			// TODO fix logging
			e.printStackTrace();
		}
		
		return attachments;
	}

	public static List<MetaLocation> getUserLocations(PersistenceManager pm, User user) {
		return getUserLocations(pm, user, null);
	}
	
	@SuppressWarnings("unchecked")
	public static List<MetaLocation> getUserLocations(PersistenceManager pm, User user, GeoPt centerPoint) {
		List<MetaLocation> locations = null;
		
		try {
			
			if (centerPoint!=null) {
				// TODO 'ranged' location search
			} else {
			
				Query q = pm.newQuery(MetaLocation.class);
				q.setFilter("owner == ownerParam");
				q.declareParameters("com.google.appengine.api.users.User ownerParam");
				locations = (List<MetaLocation>) q.execute(user);
				
			}
		
		} catch (Exception e) {
			// TODO fix logging
			e.printStackTrace();
		}
		
		return locations;
	}

	public static MetaLocation newUserLocation(PersistenceManager pm, User user, GeoPt geoPoint, String title) {
		return newUserLocation(pm, user, geoPoint, title, null);
	}
	
	public static MetaLocation newUserLocation(PersistenceManager pm, User user, GeoPt geoPoint, String title, String description) {
		MetaLocation newLocation = new MetaLocation();
		newLocation.setOwner(user);
		newLocation.setGeoPoint(geoPoint);
		newLocation.setTitle(title);
		newLocation.setDescription(description);
		newLocation.setCreationDate(new Date());
		
		newLocation = pm.makePersistent(newLocation);
		
		return newLocation;
	}

}
